#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
刪除調試：逐條打印 _match_condition 結果與頁頭變化
在 OperatingSystem 目錄下運行：
    python test/debug_delete.py
"""
import os
import sys
import tempfile
import shutil
import struct

CUR_DIR = os.path.dirname(os.path.abspath(__file__))
OS_DIR = os.path.dirname(CUR_DIR)
sys.path.insert(0, OS_DIR)

from storage_engine import StorageEngine
from table_schema import Column, ColumnType


def page_header(engine: StorageEngine, page_id: int):
    data = engine.get_page(page_id)
    rc, off = struct.unpack('II', data[:8])
    return rc, off


def main():
    print("🔍 調試刪除流程")
    print("=" * 50)

    tmp = tempfile.mkdtemp()
    db_path = os.path.join(tmp, "dbg_del_db")

    engine = StorageEngine(
        db_path=db_path,
        cache_size=8,
        enable_locking=False
    )

    cols = [
        Column("id", ColumnType.INT, primary_key=True),
        Column("name", ColumnType.VARCHAR, length=50),
        Column("age", ColumnType.INT),
    ]

    print("1️⃣ 建表...")
    ok = engine.create_table("t", cols)
    print(f"   結果: {'✅' if ok else '❌'}")

    print("2️⃣ 插入三條...")
    for r in (
        {"id": 1, "name": "Alice", "age": 25},
        {"id": 2, "name": "Bob", "age": 30},
        {"id": 3, "name": "Charlie", "age": 35},
    ):    
        print(f"   插入 {r} -> {'✅' if engine.insert_record('t', r) else '❌'}")

    mapping = engine.table_pages.get("t", [])
    print(f"3️⃣ 頁面映射: {mapping}")
    for pid in mapping:
        rc, off = page_header(engine, pid)
        print(f"   頁 {pid}: 記錄數={rc}, 空閒偏移={off}")

    print("4️⃣ 掃描與匹配檢查...")
    schema = engine.table_schemas["t"]
    target = {"id": 3}
    total = 0
    for pid in mapping:
        recs = engine._scan_page_records(pid, schema)
        print(f"   頁 {pid} 掃描 {len(recs)} 條")
        for rec in recs:
            d = rec.to_dict()
            m = engine._match_condition(rec, target)
            print(f"     → {d} | 匹配({target})={m}")
            if m:
                total += 1
    print(f"   匹配總數（預期>=1）: {total}")

    print("5️⃣ 執行刪除 id=3 ...")
    deleted = engine.delete_records("t", {"id": 3})
    print(f"   刪除返回: {deleted}")

    print("6️⃣ 刪除後頁頭...")
    for pid in mapping:
        rc, off = page_header(engine, pid)
        print(f"   頁 {pid}: 記錄數={rc}, 空閒偏移={off}")

    print("7️⃣ 刪除後再次掃描...")
    total_after = 0
    for pid in mapping:
        recs = engine._scan_page_records(pid, schema)
        print(f"   頁 {pid} 掃描 {len(recs)} 條")
        for rec in recs:
            print(f"     → {rec.to_dict()}")
            total_after += 1
    print(f"   掃描合計: {total_after}")

    engine.close()
    shutil.rmtree(tmp)


if __name__ == "__main__":
    main()
